<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名字" prop="khname">
        <el-input
          v-model="queryParams.khname"
          placeholder="请输入客户名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户地址" prop="khdz">
        <el-input
          v-model="queryParams.khdz"
          placeholder="请输入客户地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="bz">
        <el-input
          v-model="queryParams.bz"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gd:dbjlb:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gd:dbjlb:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gd:dbjlb:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gd:dbjlb:export']"
        >全部导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dbjlbList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户名字" align="center" prop="khname" />
      <el-table-column label="客户地址" align="center" prop="khdz" />
      <el-table-column label="报价类型" align="center" prop="bjfj">
        <template slot-scope="scope">
          <span>{{scope.row.bjlx === '1' ? '常规报价' : scope.row.bjlx === '2' ? '完工单报价' : scope.row.bjlx === '3' ? "常规+完工单报价" : ""}}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="生成报价单" align="center" prop="scfj" />-->
      <el-table-column label="备注" align="center" prop="bz" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.status === '0'">未生成报价单</el-tag>
          <el-tag type="success" v-else>已经成报价单</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="userName === 'admin'">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gd:dbjlb:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gd:dbjlb:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改待报价列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名字" prop="khname">
              <el-input v-model="form.khname" placeholder="请输入客户">
                <el-button type="primary" slot="prepend" @click.native="selectUser"> <i class="el-icon-user-solid"></i> </el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="客户地址" prop="khdz">
              <el-input v-model="form.khdz" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="报价类型" prop="bjlx">
              <el-radio-group v-model="form.bjlx">
                <el-radio v-for="item in bjlxList" :label="item.dictValue">{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报价日期" prop="bjrq">
              <el-date-picker clearable
                              style="width: 100%"
                              v-model="form.bjrq"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择报价时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="导入类型" prop="drlx">
              <el-checkbox-group v-model="drlx" @change="selectDrlx">
                <el-checkbox v-for="item in drlxList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="报价附件" prop="bjfj">
              <el-upload
                class="upload-demo"
                :action="src"
                name="files"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="handleRemove"
                :headers="uploadHeaders"
                accept=".xlsx, .xls"
                :limit="1"
                :file-list="fjList"
                :on-preview="handlePreview"
              >
                <span slot="trigger">
                  <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
                </span>
                <span style="margin-left: 10px" v-if="fjList.length > 0">
                  <el-button size="small" :loading="genButton" type="primary" @click="genBjd">点击生成报价单</el-button>
                </span>
                <div slot="tip" class="el-upload__tip">
                  只能上传Excel文件
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="bjeList.length > 0">
          <el-col :span="24">
            <el-form-item label="报价单数据" prop="scfj">
              <el-table
                border
                :data="bjeList">
                <el-table-column
                  prop="fjname"
                  header-align="center"
                  label="报价单名称">
                </el-table-column>
                <el-table-column
                  width="200"
                  header-align="center"
                  label="操作">
                  <template slot-scope="scope">
                    <el-button
                      @click="downFile(scope.row)"
                      type="primary"
                      icon="el-icon-download"
                      size="mini"
                    >下载</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="bz">
              <el-input v-model="form.bz" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <khList v-if="showUser" :showUser="showUser" @selectData="selectData" @closeDialog="closeDialog"></khList>
  </div>
</template>

<script>
import { listDbjlb, getDbjlb, delDbjlb, addDbjlb, updateDbjlb, genQuotation } from "@/api/gd/dbjlb";
import khList from "@/views/gd/ywd/khList.vue";
import { getToken } from '@/utils/auth'
import { delFj, getFj, getFjById } from '@/api/gd/fj'
import axios from 'axios'
export default {
  name: "Dbjlb",
  components: { khList },
  data() {
    return {
      genButton: false,
      drlx: ['yqmc'],
      drlxList: [],
      bjlxList: [],
      bjeList: [],
      // 附件上传 开始
      src: this.uploadSrc + '/gd/fj/file/batchUpload',
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      fjList: [],
      // 附件上传 结束
      userName: this.$store.getters.name,
      showUser: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 待报价列表格数据
      dbjlbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        khid: undefined,
        khname: undefined,
        khdz: undefined,
        bjfj: undefined,
        scfj: undefined,
        bz: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        khname: [
          { required: true, message: "客户名字不能为空", trigger: "blur" }
        ],
        khdz: [
          { required: true, message: "客户地址不能为空", trigger: "blur" }
        ],
        bjlx: [
          { required: true, message: "请选择导入类型", trigger: "blur" }
        ],
        bjfj: [
          { required: true, message: "报价附件不能为空", trigger: "blur" }
        ],
        bjrq: [
          { required: true, message: "请选择报价日期", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDict();
  },
  methods: {
    selectDrlx(val) {
      this.form.drlx = val.toString()
    },
    genBjd() {
      // 校验当前必填数据，必填数据都填写完毕，则进行上传
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$set(this.form, 'drlx', this.drlx.toString())
          this.genButton = true
          genQuotation(this.form).then(res => {
            if(res.code === 200) {
              this.bjeList = []
              this.bjeList.push(res.data)
              this.$message.success("已生成！")
            }
          }).finally(r => {
            this.genButton = false
          })
        }
      });
    },
    getDict() {
      // 报价类型
      this.getDicts("gd_bjlx").then(res => {
        this.bjlxList = res.data
      })
      // 导入类型
      this.getDicts("gd_drlx").then(res => {
        this.drlxList = res.data
      })
    },
    // ======  上传开始  ======
    handleSuccess(response, file, fileList) {
      if (response !== null && response !== undefined) {
        // 获取当前的上传的附件id
        let fileIds = []
        fileList.forEach(item => {
          if (item.response !== undefined) {
            fileIds.push(item.response[0].fj)
          }
        })
        this.fjList = fileList
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.form.bjfj = fileIds.toString()
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      this.$modal.confirm('请确认是否删除附件名称为：'+file.name+' 的数据?').then(() => {
        let fjId = []
        let id = file.id || file.fj || file.response[0].fj
        fjId.push(id)
        delFj(fjId).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功！")
            this.fjList = fileList
          }
        })
      }).catch(() => {
        fileList.push(file)
      })
    },
    // 文件点击回调
    async handlePreview(file) {
      let id = file.id || file.fjid || file.fj || file.response[0].fj
      const response = await axios.get(this.uploadSrc + `/gd/fj/download/` + id, { responseType: 'blob', headers: this.uploadHeaders });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 删除回调
    downFile(file) {
      // 调用删除附件功能，将附件进行删除
      getFjById(file.fjid, 'blob').then(response => {
        const binaryData = [];
        binaryData.push(response);
        let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
        const link = document.createElement('a');
        link.href = url
        link.download = file.fjname;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
    },
    // ======  上传结束  ====
    closeDialog() {
      this.showUser = false
    },
    selectUser() {
      this.showUser = true
    },
    selectData(row) {
      this.form.khid = row.id
      this.form.khname = row.khname
      this.form.khdz = row.dz
      this.closeDialog()
    },
    /** 查询待报价列列表 */
    getList() {
      this.loading = true;
      listDbjlb(this.queryParams).then(response => {
        this.dbjlbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.fjList = []
      this.bjeList = []
      this.drlx = ['yqmc']
      this.reset();
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        khid: undefined,
        khname: undefined,
        khdz: undefined,
        bjfj: undefined,
        scfj: undefined,
        bz: undefined,
        status: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$set(this.form, 'bjlx', '1')
      this.open = true;
      this.title = "添加待报价列";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getDbjlb(id).then(async response => {
        let obj = response.data
        if (obj.bjfj !== "" && obj.bjfj !== null && obj.bjfj !== undefined) {
          this.fjList = []
          await getFj(obj.bjfj).then(res => {
            if (res.data !== null) {
              const data = {
                fj: res.data.fjid,
                name: res.data.fjname,
                path: res.data.fjpath
              }
              this.fjList.push(data)
            }
          })
        }
        if (obj.scfj !== "" && obj.scfj !== null && obj.scfj !== undefined) {
          this.bjeList = []
          await getFj(obj.scfj).then(res => {
            if (res.data !== null) {
              this.bjeList.push(res.data)
            }
          })
        }
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改待报价列";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.$set(this.form, 'drlx', this.drlx.toString())
          if (this.form.id != null) {
            updateDbjlb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addDbjlb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除待报价列编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delDbjlb(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gd/dbjlb/export', {
        ...this.queryParams
      }, `dbjlb_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
